package com.tiyende.kash.loop.ui.fragment

import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.common.CommonFragment
import com.tiyende.kash.loop.databinding.TiyendeFragmentAuthenticationStepAccountBinding
import com.tiyende.kash.loop.event.TiyendeEventData
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.ui.activity.TiyendeAuthenticationAccountCreateActivity
import com.tiyende.kash.loop.ui.activity.TiyendeAuthenticationStepsActivity
import com.tiyende.kash.loop.ui.adapter.TiyendeAuthenticationStepAccountAdapter
import com.tiyende.kash.loop.ui.contract.IViewContract
import com.tiyende.kash.loop.ui.dialog.TiyendeAccountCompleteDialog
import com.tiyende.kash.loop.ui.dialog.TiyendeAccountDeleteDialog
import com.tiyende.kash.loop.ui.dialog.TiyendeAccountSubmitOnlyOneDialog
import com.tiyende.kash.loop.ui.presenter.TiyendeAuthenticationStepWalletPresenter
import com.tiyende.kash.loop.utils.track.TrackPointManager
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/20 10:38
 * @Annotation：认证流程 - 法语地区绑定账户
 */
class TiyendeAuthenticationStepAccountFragment(): CommonFragment(), IViewContract.ITiyendeAuthenticationStepWalletView {
    private var _binding: TiyendeFragmentAuthenticationStepAccountBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var stepItem: JSONObject? = null
    private var eventRemark = ""
    var presenter: TiyendeAuthenticationStepWalletPresenter? = null

    private var walletAdapter: TiyendeAuthenticationStepAccountAdapter? = null

    constructor(stepItem: JSONObject): this(){
        eventRemark = stepItem.optString("stepTitle")
        this.stepItem = stepItem
    }

    override fun getTiyendeRootView(inflater: LayoutInflater): View {
        _binding = TiyendeFragmentAuthenticationStepAccountBinding.inflate(inflater)
        return binding.root
    }

    override fun initTiyendeView() {
        initAuthStepWalletListView()

        //提交按钮移到外层，通过通知的方式控制提交
        _binding?.walletNext?.visibility = View.INVISIBLE
    }

    override fun initTiyendeListener() {
        //添加
        _binding?.walletAdd?.setOnClickListener {
            showBinCardAddDialog()
        }

        //提交
        _binding?.walletNext?.setOnClickListener {
            onTiyendeSubmitAuthenticationInfoAction()
        }
    }

    override fun loadTiyendeData() {
        addEventPointRequestAction(String.format(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_XX_START,eventRemark))
        if (presenter == null){
            presenter = TiyendeAuthenticationStepWalletPresenter(this)
        }
        presenter?.requestAuthStepWalletListAction()
    }

    /**
     * 初始化Views
     */
    private fun initAuthStepWalletListView(){
        _binding?.walletListView?.isNestedScrollingEnabled = false
        _binding?.walletListView?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.walletListView?.layoutManager = layoutManager
        walletAdapter = TiyendeAuthenticationStepAccountAdapter(_binding?.walletListView)
        _binding?.walletListView?.adapter = walletAdapter
        _binding?.walletListView?.itemAnimator = DefaultItemAnimator()
        walletAdapter?.setOnItemChildClickListener { _, childView, position ->
            val item = walletAdapter?.getItem(position)
            when(childView.id){
                R.id.walletEdit -> {//添加
                    showBinCardAddDialog()
                }
                R.id.walletDelete -> {//删除
                    item?.let {
                        showDeleteDialog(it)
                    }
                }
            }
        }
    }

    /**
     * 已绑定账户列表
     */
    override fun showTiyendeAuthenticationStepWalletList(accountList: ArrayList<JSONObject>) {
        walletAdapter?.data = accountList

        walletAdapter?.let {
            //最多添加10个账户
            _binding?.walletAdd?.isEnabled = it.itemCount < 10
        }
    }

    /**
     * 添加绑卡dialog
     */
    private fun showBinCardAddDialog(){
        addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_ACCOUNT_ADD,eventRemark)
        onIntent(TiyendeAuthenticationAccountCreateActivity::class.java)
    }

    /**
     * 只有一个账户警告提示
     */
    private fun showSubmitWarningDialog(){
        val submitOnlyOneDialog = TiyendeAccountSubmitOnlyOneDialog(requireContext(),eventRemark,object : TiyendeAccountSubmitOnlyOneDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view?.id){
                    R.id.walletWarningNoMore -> {//提交(不再有账户)
                        // TODO: 发送通知，更新主流程
                        val act = getAct() as TiyendeAuthenticationStepsActivity
                        act.showTiyendeAuthenticationStepSubmitSuccess()
                    }
                    R.id.walletWarningAdd -> {//继续添加
                        showBinCardAddDialog()
                    }
                }
            }
        })
        submitOnlyOneDialog.setCancelable(true)
        submitOnlyOneDialog.setCanceledOnTouchOutside(true)
        submitOnlyOneDialog.show()
    }

    /**
     * 确认dialog
     */
    private fun showConfirmDialog(){
        walletAdapter?.let {
            val submitDialog = TiyendeAccountCompleteDialog(requireContext(),object : TiyendeAccountCompleteDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.walletSubmit){
                        addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_ACCOUNT_SUBMIT_TIPS_CONFIRM,"")
                        // TODO: Step Next 批量埋点上报
                        TrackPointManager.getInstance().manualReport()

                        // TODO: 发送通知，更新主流程
                        val act = getAct() as TiyendeAuthenticationStepsActivity
                        act.showTiyendeAuthenticationStepSubmitSuccess()
                    }
                }
            })
            submitDialog.show()
            submitDialog.setBindAccountList(it.data)
        }
    }

    /**
     * 删除提示
     */
    private fun showDeleteDialog(item: JSONObject){
        addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_ACCOUNT_DELETE,item.optString("id"))
        val deleteDialog = TiyendeAccountDeleteDialog(requireContext(),eventRemark, object : TiyendeAccountDeleteDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.walletDeleteConfirm){
                    presenter?.onDeleteAuthStepWalletAction(item.optString("id"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(true)
        deleteDialog.show()
        deleteDialog.setBindAccountInfo(item)
    }

    /**
     * 提交按钮是否可点
     */
    private fun isStepSubmit(): Boolean{
        //提交按钮是否可点
        var submitIsEnabled = false
        walletAdapter?.let {
            for (i in 0..<it.itemCount){
                //存在一个不是编辑状态的item，则可以提交
                if (!it.getItem(i).optBoolean("isEdit",true)){
                    submitIsEnabled = true
                    break
                }
            }
        }
        return submitIsEnabled
    }

    /**
     * 检查提交
     */
    private fun onCheckSubmitStatus(){
        var count = 0
        walletAdapter?.let { it ->
            it.data.forEach {
                //不是编辑类型
                if (!it.optBoolean("isEdit",true)){
                    count += 1
                }
            }
        }
        //只有一个账户，需要提示
        if (count <= 1){
            showSubmitWarningDialog()
            return
        }
        //预览所有账户列表
        showConfirmDialog()
    }

    /**
     * 提交进件信息
     */
    private fun onTiyendeSubmitAuthenticationInfoAction(){
        _binding?.root?.clearFocus()
        addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_NEXT, eventRemark),"")
        if (!isStepSubmit()){
            showErrorTipsDialog(getString(R.string.tiyende_dialog_tips_submit_error), eventRemark)
            return
        }
        onCheckSubmitStatus()
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_WALLET_REFRESH -> {//刷新已添加账户列表
                presenter?.requestAuthStepWalletListAction()
            }
            TiyendeEventData.TYPE.TIYENDE_SUBMIT_AUTHENTICATION -> {//提交数据
                onTiyendeSubmitAuthenticationInfoAction()
            }
            else -> {

            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(String.format(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_XX_END,eventRemark))
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}